
//
//  ConfirmOderViewController.m
//  GoBigMarket
//
//  Created by legend on 16/8/22.
//  Copyright © 2016年 legend. All rights reserved.
//

#import "ConfirmOderViewController.h"
#import "ConfirmFooterView.h"
#import "ConfirmHeaderView.h"
#import "ConfirmGoodCell.h"
#import "ConfirmBottomToolView.h"
#import "BWYShoppingCarModel.h"
#import "ConfirmShopModel.h"
#import "ConfirmGoodsModel.h"
#import "HomeModel.h"
#import <AlipaySDK/AlipaySDK.h>
#import "Order.h"
#import "ShopingCartViewController.h"
#import "HomeViewController.h"
#import "WXApi.h"
#import "RootViewController.h"

#import "MyProductsTool.h"
#import "MyProductModel.h"
#import "BeeCloud.h"

@interface ConfirmOderViewController ()<UITableViewDelegate, UITableViewDataSource,WXApiDelegate, UITextFieldDelegate, BeeCloudDelegate>{
    float _lng;
    float _lat;
}

@property (nonatomic, strong) NSMutableString *encodeStr;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (nonatomic, strong) NSMutableString *temp;
@property (nonatomic, strong) NSMutableString *remarkString;
@property (nonatomic ,strong) NSMutableArray *goodDataArr;
@property (nonatomic, strong) ConfirmShopModel *model;
@property (nonatomic, strong) NSString *orderStr;
@property (nonatomic, strong) ConfirmBottomToolView *tool;
@end

@implementation ConfirmOderViewController

- (void)addressNoticeCenter {
    //获取通知中心单例对象
    NSNotificationCenter * center = [NSNotificationCenter defaultCenter];
    //添加当前类对象为一个观察者，name和object设置为nil，表示接收一切通知
    [center addObserver:self selector:@selector(addresss) name:@"addressChange" object:nil];
}
- (void)addresss {
    [self creatFooterHeader];
}
- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"addressChange" object:self];
}
#pragma mark - VC加载完成
- (void)viewDidLoad {
    [super viewDidLoad];
    [self addressNoticeCenter];
    
    [BeeCloud setBeeCloudDelegate:self];
    self.remarkString = [NSMutableString string];
    self.navigationItem.title = @"确认订单";
//    [self getLastAddressData];
    [self handleData];
    [self createBottomTool];
    [self.tableView registerNib:[UINib nibWithNibName:@"ConfirmGoodCell" bundle:nil] forCellReuseIdentifier:@"ConfirmGoodCell"];
    [self creatFooterHeader];
    
    
}


- (void)addressChange:(NSNotification *)sender {
    [self creatFooterHeader];
}
#pragma mark - VC将要消失
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    
    [self.confirmArr removeAllObjects];
    self.navigationController.tabBarController.tabBar.hidden = NO;
}
#pragma mark - VC将要出现
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.navigationController.tabBarController.tabBar.hidden = YES;
    [BeeCloud setBeeCloudDelegate:self];
    //获取通知中心单例对象
    NSNotificationCenter * center = [NSNotificationCenter defaultCenter];
    //添加当前类对象为一个观察者，name和object设置为nil，表示接收一切通知
    [center addObserver:self selector:@selector(addressChange:) name:@"addressChanged" object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
}

- (void)keyboardWillShow:(NSNotification *)notification {
    /*
     Reduce the size of the text view so that it's not obscured by the keyboard.
     Animate the resize so that it's in sync with the appearance of the keyboard.
     */
    NSDictionary *userInfo = [notification userInfo];
    // Get the origin of the keyboard when it's displayed.
    NSValue* aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    // Get the top of the keyboard as the y coordinate of its origin in self's view's coordinate system. The bottom of the text view's frame should align with the top of the keyboard's final position.
    CGRect keyboardRect = [aValue CGRectValue];
    keyboardRect = [self.view convertRect:keyboardRect fromView:nil];
    
    CGFloat keyboardTop = keyboardRect.origin.y;
    CGRect tableViewFrame = self.view.bounds;
    tableViewFrame.size.height = keyboardTop - self.view.bounds.origin.y;
    
    // Get the duration of the animation.
    NSValue *animationDurationValue = [userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];
    NSTimeInterval animationDuration;
    [animationDurationValue getValue:&animationDuration];
    
    // Animate the resize of the text view's frame in sync with the keyboard's appearance.
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:animationDuration];
    
    _tableView.frame = CGRectMake(0,0,kScreenWidth, keyboardTop+50);
    [UIView commitAnimations];
}
- (void)keyboardWillHide:(NSNotification *)notification {
    
    NSDictionary* userInfo = [notification userInfo];
    /*
     Restore the size of the text view (fill self's view).
     Animate the resize so that it's in sync with the disappearance of the keyboard.
     */
    NSValue *animationDurationValue = [userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];
    NSTimeInterval animationDuration;
    [animationDurationValue getValue:&animationDuration];
    
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:animationDuration];
    _tableView.frame = CGRectMake(0,0,kScreenWidth, kScreenHeight-50);
    [UIView commitAnimations];
}

#pragma mark - 确认订单请求数据
- (void)handleData {
    self.goodDataArr = [NSMutableArray array];
    self.temp = [NSMutableString string];
    for (BWYShoppingCarModel * model in self.confirmArr) {
        if (self.confirmArr.count == 1) {
            self.temp = [NSString stringWithFormat:@"%ld",model.CartItemId].mutableCopy;
        }else {
            if (model == self.confirmArr.lastObject) {
                NSString *strShopingID = [NSString stringWithFormat:@"%ld",model.CartItemId];
                self.temp = [self.temp stringByAppendingString:strShopingID].mutableCopy;
            }else {
                NSString *strShopingID = [NSString stringWithFormat:@"%ld,",model.CartItemId];
                self.temp = [self.temp stringByAppendingString:strShopingID].mutableCopy;
            }
        }
        
    }
    
    [CQNetWorkTools GETWithURL:ShopCartOrderSubmit par:@{@"ShouJiHao":GETPHONE,@"Token":GETTOKEN,
                                                         @"Duuid":GETUUID,@"ShoppingCartId":self.temp} success:^(id responseObject) {
                                                             self.model = [ConfirmShopModel modelWithDictionary:responseObject];
                                                             NSArray *OrderSubmitArr = [responseObject objectForKey:@"OrderSubmitItem"];
                                                             for (NSDictionary *dic in OrderSubmitArr) {
                                                                 ConfirmGoodsModel *models =[ConfirmGoodsModel modelWithDictionary:dic];
                                                                 [self.goodDataArr addObject:models];
                                                             }
                                                             [self.tableView reloadData];
                                                             [self creatFooterHeader];
                                                             [self createBottomTool];
                                                             
                                                         } filed:^(NSError *error) {
                                                         }];
    DLog(@"%@", self.temp);
    
}
#pragma mark - 创建头部尾部视图
- (void)creatFooterHeader {
//    ConfirmFooterView *footer = [[ConfirmFooterView alloc] initWithFrame:CGRectMake(0, 0, XNWindowWidth, 200)];
//    if (sixInch) {
//        footer.hasUseSaveLb.font = [UIFont systemFontOfSize:15];
//        footer.hasCutLb.font = [UIFont systemFontOfSize:15];
//    }
//    if (FourInch) {
//        footer.hasUseSaveLb.font = [UIFont systemFontOfSize:13];
//        footer.hasCutLb.font = [UIFont systemFontOfSize:13];
//    }
//    self.remarkString = footer.remarkText.text.mutableCopy;
    ConfirmHeaderView *header =[[ConfirmHeaderView alloc] initWithFrame:CGRectMake(0, 0, XNWindowWidth, XNWindowHeight/2.37)];
    header.saveMoney.text = [NSString stringWithFormat:@"%.2f元", self.model.CouponPrice];
    self.remarkString = header.remarkText.text.mutableCopy;
    header.remarkText.delegate = self;
    if (sixInch) {
        header.shopName.font = [UIFont systemFontOfSize:15];
        header.receiveAddressLb.font = [UIFont systemFontOfSize:15];
        header.manNameLb.font = [UIFont systemFontOfSize:15];
        header.phoneLb.font = [UIFont systemFontOfSize:15];
        header.reciveAdress.font = [UIFont systemFontOfSize:15];
        header.manName.font = [UIFont systemFontOfSize:15];
        header.phoneNumber.font = [UIFont systemFontOfSize:15];
    }
    if (FourInch) {
        header.shopName.font = [UIFont systemFontOfSize:12];
        header.receiveAddressLb.font = [UIFont systemFontOfSize:12];
        header.manNameLb.font = [UIFont systemFontOfSize:12];
        header.phoneLb.font = [UIFont systemFontOfSize:12];
        header.reciveAdress.font = [UIFont systemFontOfSize:13];
        header.manName.font = [UIFont systemFontOfSize:13];
        header.phoneNumber.font = [UIFont systemFontOfSize:13];
    }
    header.shopName.text = self.model.shopName;
    header.phoneNumber.text = GETShipToPhone;
    header.reciveAdress.text = GETShipToAddress;
    header.manName.text = GETShipTo;
    self.tableView.tableHeaderView = header;
}
#pragma mark - 创建底部工具栏
- (void)createBottomTool {
    self.tool = [[ConfirmBottomToolView alloc] initWithFrame:CGRectMake(0, XNWindowHeight -114, XNWindowWidth, 50)];
    self.tool.layer.borderWidth = 1;
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    CGColorRef colorref = CGColorCreate(colorSpace,(CGFloat[]){ 230/255.f, 230/255.f, 230/255.f, 1 });
    
    [self.tool.layer setBorderColor:colorref];//边框颜色
    [self.tool.payBtn addTarget:self action:@selector(payAction) forControlEvents:UIControlEventTouchUpInside];
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%.2f元", self.model.OrderAmount]];
    
    [attributedString addAttribute:NSForegroundColorAttributeName value:XNColor(236, 152, 18, 1) range:NSMakeRange(0, attributedString.length)];
    [attributedString addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:25] range:NSMakeRange(0, attributedString.length -1)];
    self.tool.totalPrice.attributedText = attributedString;
    
    NSMutableAttributedString *attributedStringSave = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%.2f元", self.model.CouponPrice]];
    
    [attributedStringSave addAttribute:NSForegroundColorAttributeName value:XNColor(236, 152, 18, 1) range:NSMakeRange(0, [NSString stringWithFormat:@"%.2f元", self.model.CouponPrice].length-1)];
    
    [attributedStringSave addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:25] range:NSMakeRange(0, [NSString stringWithFormat:@"%.2f元", self.model.CouponPrice].length -1)];
    self.tool.savePrice.attributedText = attributedStringSave;
    if (sixInch) {
        self.tool.waitPayLb.font = [UIFont systemFontOfSize:15];
        self.tool.hasSaveLb.font = [UIFont systemFontOfSize:15];
        [attributedStringSave addAttribute:NSForegroundColorAttributeName value:XNColor(236, 152, 18, 1) range:NSMakeRange(0, [NSString stringWithFormat:@"%.2f元", self.model.CouponPrice].length)];
        [attributedStringSave addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:22] range:NSMakeRange(0, [NSString stringWithFormat:@"%.2f元", self.model.CouponPrice].length -1)];
        self.tool.savePrice.attributedText = attributedStringSave;
        
        NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%.2f元", self.model.OrderAmount]];
        
        [attributedString addAttribute:NSForegroundColorAttributeName value:XNColor(236, 152, 18, 1) range:NSMakeRange(0, attributedString.length)];
        [attributedString addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:22] range:NSMakeRange(0, attributedString.length -1)];
        self.tool.totalPrice.attributedText = attributedString;
    }
    /* 5/5s适配*/
    if (FourInch) {
        self.tool.waitPayLb.font = [UIFont systemFontOfSize:13];
        self.tool.hasSaveLb.font = [UIFont systemFontOfSize:13];
        [attributedStringSave addAttribute:NSForegroundColorAttributeName value:XNColor(236, 152, 18, 1) range:NSMakeRange(0, [NSString stringWithFormat:@"%.2f元", self.model.CouponPrice].length)];
        [attributedStringSave addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:20] range:NSMakeRange(0, [NSString stringWithFormat:@"%.2f元", self.model.CouponPrice].length -1)];
        self.tool.savePrice.attributedText = attributedStringSave;
        
        NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%.2f元", self.model.OrderAmount]];
        
        [attributedString addAttribute:NSForegroundColorAttributeName value:XNColor(236, 152, 18, 1) range:NSMakeRange(0, attributedString.length)];
        [attributedString addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:20] range:NSMakeRange(0, attributedString.length -1)];
        self.tool.totalPrice.attributedText = attributedString;
    }
    [self.view addSubview:self.tool];
}

#pragma mark - 支付按钮点击事件
- (void)payAction {
    if (GETShipToAddressId == nil) {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"请填写增收货地址信息" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        [alert addAction:action1];
        [self presentViewController:alert animated:YES completion:^{
            
        }];
    }else {
        [self testReceiveAddress];
    }
}
#pragma mark - 验证收货地址
- (void)testReceiveAddress {
    
//    DLog(@"%@#%@#%@#%@#%@#",GETPHONE, GETTOKEN,GETUUID,GETShipToAddressId,[NSString stringWithFormat:@"%d", self.model.ShopId]);
    [CQNetWorkTools GETWithURL:ConfirmReceiveAddress par:@{@"ShouJiHao":GETPHONE,@"Token":GETTOKEN,@"Duuid":GETUUID,@"AddressId":GETShipToAddressId,@"ShopId":[NSString stringWithFormat:@"%d", self.model.ShopId]} success:^(id responseObject){
        if ([[responseObject objectForKey:@"Err"]integerValue] != 0) {
            
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:[responseObject objectForKey:@"ErrMsg"] preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                
            }];
            [alert addAction:action1];
            [self presentViewController:alert animated:YES completion:^{
                
            }];
        }else {
            
            [self confirmOrder];
        }
        
        
    } filed:^(NSError *error) {
        
    }];
}

#pragma mark - 发送确认订单请求
- (void)confirmOrder {
    [CQNetWorkTools POSTWithURL:ShopCartSubmitOrder par:@{@"ShouJiHao":GETPHONE,@"Token":GETTOKEN,@"Duuid":GETUUID,@"ShoppingCartId":self.temp,@"RecieveAddressId":GETShipToAddressId,@"CouponRecordId":[NSString stringWithFormat:@"%d", self.model.CouponRecordId],@"ShopId":[NSString stringWithFormat:@"%d", self.model.ShopId],@"Remark":self.remarkString} success:^(id responseObject) {
        if ([[responseObject objectForKey:@"Err"]integerValue] != 0) {
            NSLog(@"错误%@", [responseObject objectForKey:@"ErrMsg"]);
            
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:[responseObject objectForKey:@"ErrMsg"] preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                
            }];
            [alert addAction:action1];
            [self presentViewController:alert animated:YES completion:^{
                
            }];
        }else {
            
            self.orderStr = [responseObject objectForKey:@"OrderId"];
            [self pullAlert];
        }
        
    } filed:^(NSError *error) {
        DLog(@"购物车提交订单错误%@", error);
    }];
}

#pragma mark - 选择支付方式
- (void)pullAlert {
    UIAlertController *sheetController = [UIAlertController alertControllerWithTitle:@"请选择支付方式" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"支付宝支付" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self goCount];
    }];
    UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"微信支付" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self beeCloudPayOrder];
    }];
    UIAlertAction *action3 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        DLog(@"取消");
    }];
#warning Cancel按钮一直在最下边，并且上拉菜单类型不可以添加文本框
    [sheetController addAction:action1];
    [sheetController addAction:action2];
    [sheetController addAction:action3];
    [self presentViewController:sheetController animated:YES completion:^{
        
    }];
}
#pragma mark - beeCloud 微信去支付
- (void)beeCloudPayOrder {
    [CQNetWorkTools POSTWithURL:beeCloudSubmitOrder par:@{@"ShouJiHao":GETPHONE,@"Token":GETTOKEN,@"Duuid":GETUUID,@"OrderId":self.orderStr,@"PlatType": @"IOS"} success:^(id responseObject) {
        
        NSString *BillNum =[responseObject objectForKey:@"BillNum"];
        NSString *BillTitle =[responseObject objectForKey:@"BillTitle"];
        NSString *BillTotalFee =[responseObject objectForKey:@"BillTotalFee"];
       NSString *PayId = [responseObject objectForKey:@"PayId"];
        [self doPay:PayChannelWxApp BillNum:BillNum BillTitle:BillTitle BillTotalFee:BillTotalFee PayId:PayId];
    } filed:^(NSError *error) {
        
    }];
}
#pragma mark - beeCloud支付
- (void)doPay:(PayChannel)channel BillNum:(NSString *)BillNum BillTitle:(NSString *)BillTitle BillTotalFee:(NSString *)BillTotalFee PayId:(NSString *)PayId{
    NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithObjectsAndKeys:@"value",@"key", nil];
    /**
     按住键盘上的option键，点击参数名称，可以查看参数说明
     **/
    BCPayReq *payReq = [[BCPayReq alloc] init];
    /**
     *  支付渠道，PayChannelWxApp,PayChannelAliApp,PayChannelUnApp,PayChannelBaiduApp
     */
    
    
    payReq.channel = channel; //支付渠道
    payReq.title = BillTitle;//订单标题
    payReq.totalFee = [NSString stringWithFormat:@"%@", BillTotalFee];//订单价格; channel为BC_APP的时候最小值为100，即1元
    payReq.billNo = [NSString stringWithFormat:@"%@", BillNum];//商户自定义订单号
    
    payReq.scheme = @"wxdeaf20c134765733";//URL Scheme,在Info.plist中配置; 支付宝必有参数
    payReq.billTimeOut = 300;//订单超时时间
    payReq.viewController = self; //银联支付和Sandbox环境必填
    payReq.cardType = 0; //0 表示不区分卡类型；1 表示只支持借记卡；2 表示支持信用卡；默认为0
    payReq.optional = dict;//商户业务扩展参数，会在webhook回调时返回
    [BeeCloud sendBCReq:payReq];
}
#pragma mark - 支付宝去结算方法
- (void)goCount {
    self.encodeStr = [NSMutableString string];
    [CQNetWorkTools POSTWithURL:ShopCartGoPay par:@{@"ShouJiHao":GETPHONE,@"Token":GETTOKEN,@"Duuid":GETUUID,@"OrderId":self.orderStr,@"PlatType": @"IOS"} success:^(id responseObject) {
        DLog(@"去结算成功%@", [responseObject objectForKey:@"Parm"]);
        NSString *parm = [responseObject objectForKey:@"Parm"];
        NSArray *array = [parm componentsSeparatedByString:@"&"];
        DLog(@"%@", array);
        Order* order = [Order new];
        // NOTE: 商品数据
        order.biz_content = [BizContent new];
        for (int i =0 ; i < array.count; i++) {
            NSString *str = [array objectAtIndex:i];
            NSArray *arr = [str componentsSeparatedByString:@"="];
            NSString *string = [NSString string];
            if (arr.count == 3) {
                string = [[arr objectAtIndex:1]  stringByAppendingString:@"="];
            }else {
            string = [arr lastObject];
            }
            NSString *key = [arr firstObject];
            switch (i) {
                case 0:{
                    // NOTE: app_id设置
                    order.app_id = string;
                    DLog(@"软件号码%@", self.encodeStr);
                    self.encodeStr = [[[[self.encodeStr stringByAppendingString:key]stringByAppendingString:@"="]stringByAppendingString:order.app_id]stringByAppendingString:@"&"].mutableCopy;
                }
                    break;
                case 1:{
                    DLog(@"方法%@", self.encodeStr);
                    // NOTE: 支付接口名称
                    order.method = string;
                    self.encodeStr = [[[[self.encodeStr stringByAppendingString:key]stringByAppendingString:@"="]stringByAppendingString:order.method]stringByAppendingString:@"&"].mutableCopy;
                }
                    break;
                case 2:{
                    DLog(@"方式%@", self.encodeStr);
                    order.charset = string;
                    self.encodeStr = [[[[self.encodeStr stringByAppendingString:key]stringByAppendingString:@"="]stringByAppendingString:order.charset]stringByAppendingString:@"&"].mutableCopy;
                }
                    break;
                case 3:{
                    DLog(@"加签格式%@", self.encodeStr);
                    // NOTE: 参数编码格式
                    order.sign_type = string;
                    self.encodeStr = [[[[self.encodeStr stringByAppendingString:key]stringByAppendingString:@"="]stringByAppendingString:order.sign_type]stringByAppendingString:@"&"].mutableCopy;
                }
                    break;
                case 4:{
                    DLog(@"时间%@", self.encodeStr);
                    // NOTE: 当前时间点
                    order.timestamp = (__bridge_transfer  NSString*)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (__bridge CFStringRef)string, NULL, (__bridge CFStringRef)@"!*'();:@&=+$,/?%#[]", kCFStringEncodingUTF8 );
                    self.encodeStr = [[[[self.encodeStr stringByAppendingString:key]stringByAppendingString:@"="]stringByAppendingString:order.timestamp]stringByAppendingString:@"&"].mutableCopy;
                }
                    break;
                case 5:{
                    // NOTE: 支付版本
                    order.version = string;
                    self.encodeStr = [[[[self.encodeStr stringByAppendingString:key]stringByAppendingString:@"="]stringByAppendingString:order.version]stringByAppendingString:@"&"].mutableCopy;
                }
                    break;
                case 6:
                {
                    order.notify_url = (__bridge_transfer  NSString*)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (__bridge CFStringRef)string, NULL, (__bridge CFStringRef)@"!*'();:@&=+$,/?%#[]", kCFStringEncodingUTF8 );
                    self.encodeStr = [[[[self.encodeStr stringByAppendingString:key]stringByAppendingString:@"="]stringByAppendingString:order.notify_url]stringByAppendingString:@"&"].mutableCopy;
                }
                    break;
                case 7:{
                    // NOTE: sign_type设置
                    order.biz = (__bridge_transfer  NSString*)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (__bridge CFStringRef)string, NULL, (__bridge CFStringRef)@"!*'();:@&=+$,/?%#[]", kCFStringEncodingUTF8 );
                    self.encodeStr = [[[[self.encodeStr stringByAppendingString:key]stringByAppendingString:@"="]stringByAppendingString:order.biz]stringByAppendingString:@"&"].mutableCopy;
                    }
                    break;
                case 8:{
                    order.sign = (__bridge_transfer  NSString*)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (__bridge CFStringRef)string, NULL, (__bridge CFStringRef)@"!*'();:@&=+$,/?%#[]", kCFStringEncodingUTF8 );
                    self.encodeStr = [[[[self.encodeStr stringByAppendingString:key]stringByAppendingString:@"="]stringByAppendingString:order.sign]stringByAppendingString:@"="].mutableCopy;
                }
                    break;
                default:
                    break;
            }
        }
        NSString *appScheme = @"wxdeaf20c134765733";
        // NOTE: 调用支付结果开始支付
        [[AlipaySDK defaultService] payOrder:self.encodeStr fromScheme:appScheme callback:^(NSDictionary *resultDic) {
            
            if ( [[resultDic objectForKey:@"resultStatus"] intValue]== 9000)
            {
                UIStoryboard *story=[UIStoryboard storyboardWithName:@"Main" bundle:nil];
                RootViewController *rootVC = [story instantiateViewControllerWithIdentifier:@"tabBarId"];
                self.view.window.rootViewController = rootVC;
                rootVC.selectedIndex = 0;
//                [self CartRedPoint];
            }
        }];
        
    } filed:^(NSError *error) {
        DLog(@"去结算失败%@", error);                         }];
    /**
     *  删除数据库全部购物车商品信息
     */
    [MyProductsTool deleteAllProductsFromSQL];
    /**
     *  购物车数据保存到数据库(程序启动时调用一次,不能重复调用)
     */
    [MyProductsTool getShopCartInfoRequest];
}
//#pragma mark - 小红点
//- (void)CartRedPoint {
//    if (GETShopId) {
//    [CQNetWorkTools POSTWithURL:ShopCartGetProducts par:@{@"ShouJiHao":GETPHONE,@"Token":GETTOKEN, @"Duuid":GETUUID,@"ShopId":GETShopId} success:^(id responseObject) {
//        
//        self.navigationController.tabBarController.viewControllers[2].tabBarItem.badgeValue = [NSString stringWithFormat:@"%@", [responseObject objectForKey:@"TotalCount"]];
//        if ([[NSString stringWithFormat:@"%@", [responseObject objectForKey:@"TotalCount"]] isEqualToString:@"0"]) {
//            self.navigationController.tabBarController.viewControllers[2].tabBarItem.badgeValue = nil;
//        }
//    } filed:^(NSError *error) {
//        NSLog(@"%@", error);
//    }];
//    }
//}

#pragma mark - TableView的dataSource协议方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.goodDataArr.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    ConfirmGoodCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ConfirmGoodCell"];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    [cell setModel:[self.goodDataArr objectAtIndex:indexPath.row]];
    return cell;
}
#pragma mark - 行高
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 100;
}
#pragma mark - UITextfieldDelegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];
    return YES;
}
#pragma mark - 微信支付回调
- (void)onBeeCloudResp:(BCBaseResp *)resp {
    
    switch (resp.type) {
        case BCObjsTypePayResp:
        {
            
            // 支付请求响应
            BCPayResp *tempResp = (BCPayResp *)resp;
            if (tempResp.resultCode == 0) {
                UIStoryboard *story=[UIStoryboard storyboardWithName:@"Main" bundle:nil];
                RootViewController *rootVC = [story instantiateViewControllerWithIdentifier:@"tabBarId"];
                self.view.window.rootViewController = rootVC;
                rootVC.selectedIndex = 0;
                BCPayReq *payReq = (BCPayReq *)resp.request;
                //百度钱包比较特殊需要用户用获取到的orderInfo，调用百度钱包SDK发起支付
                if (payReq.channel == PayChannelBaiduApp && ![BeeCloud getCurrentMode]) {
                    
                } else {
                    //微信、支付宝、银联支付成功
                    self.tabBarController.selectedIndex = 0;
                }
            } else {
                //支付取消或者支付失败
                UIStoryboard *story=[UIStoryboard storyboardWithName:@"Main" bundle:nil];
                RootViewController *rootVC = [story instantiateViewControllerWithIdentifier:@"tabBarId"];
                self.view.window.rootViewController = rootVC;
                rootVC.selectedIndex = 0;
                [self showAlertView:[NSString stringWithFormat:@"%@ : %@",tempResp.resultMsg, tempResp.errDetail]];
            }
        }
            break;
        case BCObjsTypeQueryBillsResp:
        {
            
            BCQueryBillsResp *tempResp = (BCQueryBillsResp *)resp;
            if (resp.resultCode == 0) {
                if (tempResp.count == 0) {
                    [self showAlertView:@"未找到相关订单信息"];
                } else {
                    
                    [self performSegueWithIdentifier:@"queryResult" sender:self];
                }
            } else {
                [self showAlertView:[NSString stringWithFormat:@"%@ : %@",tempResp.resultMsg, tempResp.errDetail]];
            }
        }
            break;
        case BCObjsTypeQueryRefundsResp:
        {
            
            BCQueryRefundsResp *tempResp = (BCQueryRefundsResp *)resp;
            if (resp.resultCode == 0) {
                if (tempResp.count == 0) {
                    [self showAlertView:@"未找到相关订单信息"];
                } else {
                   
                    [self performSegueWithIdentifier:@"queryResult" sender:self];
                }
            } else {
                [self showAlertView:[NSString stringWithFormat:@"%@ : %@",tempResp.resultMsg, tempResp.errDetail]];
            }
        }
            break;
        default:
        {
            if (resp.resultCode == 0) {
                [self showAlertView:resp.resultMsg];
            } else {
                [self showAlertView:[NSString stringWithFormat:@"%@ : %@",resp.resultMsg, resp.errDetail]];
            }
        }
            break;
    }
}

- (void)showAlertView:(NSString *)msg {
    UIAlertView* alert = [[UIAlertView alloc]initWithTitle:@"提示" message:msg delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
    [alert show];
}

#pragma mark -
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}
@end
